package com.ktwlsoft.fundmanage.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ktwlsoft.fundmanage.domain.entity.DataDictionary;
import com.ktwlsoft.fundmanage.domain.repository.DataDictionaryRepository;
import com.ktwlsoft.fundmanage.mapper.CurrencyMapper;
import com.ktwlsoft.fundmanage.payload.BaseResult;
import com.ktwlsoft.fundmanage.payload.IAccountUser;
import com.ktwlsoft.fundmanage.payload.ResultType;
import com.ktwlsoft.fundmanage.utils.KeyWorkerUtil;
import com.ktwlsoft.fundmanage.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 数据字典
 *
 * @author Name on 2019/9/4 16:18
 * @version 1.0
 */
@Service
public class DataDictionaryService {

    /** 日志对象 **/
    private static Logger logger = LoggerFactory.getLogger(DataDictionaryService.class);

    private final DataDictionaryRepository dataDictionaryRepository;

    /**通用*/
    private final CurrencyMapper currencyMapper;

    public DataDictionaryService(DataDictionaryRepository dataDictionaryRepository, CurrencyMapper currencyMapper){
        this.dataDictionaryRepository = dataDictionaryRepository;
        this.currencyMapper = currencyMapper;
    }

    /**
      * 新增或修改数据字典 on 2019/9/4 16:28
      *
      * @param dataDictionary 字典对象
      * @return BaseResult<?>
      */
    public BaseResult<?> save(DataDictionary dataDictionary){
        IAccountUser user = UserUtils.getUser();
        if(dataDictionary.getId() == null){
            dataDictionary.setId(KeyWorkerUtil.nextId());
            dataDictionary.setState(DataDictionary.DicState.USING);
            dataDictionary.setCreatorId(user.getUserId());
            dataDictionary.setCreatorName(user.getName());
            dataDictionary.setCreatedAt(new Date());
        }
        if(dataDictionary.getParentId() == null || dataDictionary.getParentId() < 0){
            dataDictionary.setParentId(0L);
        }
        List<DataDictionary> list = dataDictionaryRepository.findByParentId(dataDictionary.getId());
        if(list != null && list.size() > 0){
            return BaseResult.body(dataDictionary,ResultType.BUSINESS_ERROR).withMessage("该数据存在子级,不可修改");
        }
        dataDictionary.setUpdateId(user.getUserId());
        dataDictionary.setUpdateName(user.getName());
        dataDictionary.setUpdatedAt(new Date());
        try {
            dataDictionaryRepository.save(dataDictionary);
        }catch (Exception e){
            logger.error(e.getMessage());
            return BaseResult.body(null, ResultType.BUSINESS_ERROR);
        }
        return BaseResult.body(dataDictionary,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 软删除 on 2019/9/4 17:06
      *
      * @param dataDictionary dataDictionary
      * @return BaseResult<?>
      */
    public BaseResult<?> deleteById(DataDictionary dataDictionary){
        dataDictionary.setState(DataDictionary.DicState.DELETED);
        try {
            dataDictionaryRepository.save(dataDictionary);
        }catch (Exception e){
            logger.error(e.getMessage());
            return BaseResult.body(null,ResultType.BUSINESS_ERROR);
        }
        return BaseResult.body(dataDictionary,ResultType.BUSINESS_SUCCESS);
    }

    /**
     * 启用禁用 on 2019/9/4 17:06
     *
     * @param id id
     * @return BaseResult<?>
     */
    public BaseResult<?> updateState(Long id){
        DataDictionary dataDictionary = dataDictionaryRepository.findById(id).orElse(null);
        if(dataDictionary == null){
            return BaseResult.body(null,ResultType.BUSINESS_ERROR).withMessage("该数据不存在");
        }
        if(dataDictionary.getState().equals(DataDictionary.DicState.STOP)){
            dataDictionary.setState(DataDictionary.DicState.USING);
        }else{
            dataDictionary.setState(DataDictionary.DicState.STOP);
        }
        try {
            dataDictionaryRepository.save(dataDictionary);
        }catch (Exception e){
            logger.error(e.getMessage());
            return BaseResult.body(null,ResultType.BUSINESS_ERROR);
        }
        return BaseResult.body(dataDictionary,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 物理删除 on 2019/9/4 16:33
      *
      * @param dataDictionary dataDictionary
      * @return BaseResult<?>
      */
    public BaseResult<?> delete(DataDictionary dataDictionary){
        List<DataDictionary> list = dataDictionaryRepository.findByParentId(dataDictionary.getId());
        if(list != null && list.size() > 0){
            return BaseResult.body(dataDictionary,ResultType.BUSINESS_ERROR).withMessage("该数据存在子级,不可删除");
        }
        try {
            dataDictionaryRepository.delete(dataDictionary);
        }catch (Exception e){
            logger.error(e.getMessage());
            return BaseResult.body(null,ResultType.DELETE_ERROR);
        }
        return BaseResult.body(dataDictionary,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 批量物理删除 on 2019/9/4 16:35
      *
      * @param dictionaries dictionaries
      * @return BaseResult<?>
      */
    public BaseResult<?> deletes(List<DataDictionary> dictionaries){
        List<DataDictionary> list = dataDictionaryRepository.findAll();
        if(list.size() > 0){
            for(DataDictionary dataDictionary:dictionaries){
                for(DataDictionary dictionary:list){
                    if(dataDictionary.getId().equals(dictionary.getParentId())){
                        return BaseResult.body(dataDictionary,ResultType.BUSINESS_ERROR).withMessage("该数据存在子级,不可删除");
                    }
                }
            }
        }
        try {
            dataDictionaryRepository.deleteAll(dictionaries);
        }catch (Exception e){
            logger.error(e.getMessage());
            return BaseResult.body(null, ResultType.DELETE_ERROR);
        }
        return BaseResult.body(dictionaries,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 分页 on 2019/9/4 16:41
      *
      * @param dataDictionary dataDictionary
      * @return BaseResult<?>
      */
    public BaseResult<?> findPage(int pn,int pageSize,DataDictionary dataDictionary){
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataDictionary));
        PageHelper.startPage(pn,pageSize);
        return BaseResult.body(new PageInfo<>(currencyMapper.dataDictionaryList(jsonObject)),ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 查询集合 on 2019/9/4 16:43
      *
      * @param dataDictionary dataDictionary
      * @return BaseResult<?>
      */
    public BaseResult<?> findList(DataDictionary dataDictionary){
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataDictionary));
        return BaseResult.body(currencyMapper.dataDictionaryList(jsonObject),ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 根据id查询数据 on 2019/9/4 16:46
      *
      * @param id id
      * @return BaseResult<?>
      */
    public BaseResult<?> getByid(Long id){
        DataDictionary dataDictionary = dataDictionaryRepository.findById(id).orElse(null);
        if(dataDictionary == null){
            return BaseResult.body(null,ResultType.BUSINESS_ERROR).withMessage("该数据不存在");
        }
        return BaseResult.body(dataDictionary,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 根据key查询数据 on 2019/9/4 16:48
      *
      * @param key key
      * @return BaseResult<?>
      */
    public BaseResult<?> getByKey(String key){
        List<DataDictionary> list = dataDictionaryRepository.findByDicKey(key);
        if(list == null || list.size() <= 0){
            return BaseResult.body(null,ResultType.BUSINESS_ERROR).withMessage("该数据不存在");
        }
        return BaseResult.body(list,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 根据父id查询数据 on 2019/9/4 16:51
      *
      * @param parentId parentId
      * @return BaseResult<?>
      */
    public BaseResult<?> getByParentId(Long parentId){
        List<DataDictionary> list = dataDictionaryRepository.findByParentId(parentId);
        if(list == null || list.size() <= 0){
            return BaseResult.body(null,ResultType.BUSINESS_ERROR).withMessage("该数据不存在");
        }
        return BaseResult.body(list,ResultType.BUSINESS_SUCCESS);
    }
}